package com.iob.coin.interceptor;

import com.alibaba.fastjson.JSON;
import com.iob.coin.config.MainConfig;
import com.iob.coin.util.logutil.Logger;
import com.iob.coin.vo.ResponseVO;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * @Author: GuoXinyuan
 * @Date: 2021/5/15
 * 身份认证拦截器
 */

public class AuthenticationInterceptor implements HandlerInterceptor {

    private static final Logger logger = new Logger(AuthenticationInterceptor.class.getSimpleName(),System.out);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();

        Object user = session.getAttribute(MainConfig.IDENTIFY_SESSION_KEY);
        if(user == null){

            logger.log("verify","验证失败",new HashMap<String,String>(){{
                put("URI",request.getRequestURI());
                put("httpSessionId",session.getId());
            }});

            response.getWriter().write(JSON.toJSONString(ResponseVO.buildFailure(MainConfig.VERIFY_FAILED_COMMAND)));
            return false;
        }

        logger.log("verify","验证成功",new HashMap<String,String>(){{
            put("URI",request.getRequestURI());
            put("httpSessionId",session.getId());
        }});

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView){
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) {
    }
}
